use crate::{
    handler::DynEndpoint, request::Request, response::Response, utils::async_trait, Result,
};
use std::{future::Future, pin::Pin, sync::Arc};

#[async_trait]
pub trait Middleware: Send + Sync + 'static {
    /// 将rapid中request转换为reponse
    async fn handle(&self, request: Request, next: Next<'_>) -> crate::Result;

    ///设置middleWare的标识符
    fn name(&self) -> &str {
        std::any::type_name::<Self>()
    }
}

pub struct Next<'a> {
    pub(crate) endpoint: &'a DynEndpoint,
    pub(crate) next_middleware: &'a [Arc<dyn Middleware>],
}

impl Next<'_> {
    /// Asynchronously execute the remaining middleware chain.
    pub async fn run(mut self, req: Request) -> Result<Response> {
        let res = if let Some((current, next)) = self.next_middleware.split_first() {
            self.next_middleware = next;
            current.handle(req, self).await?
        } else {
            self.endpoint.call(req).await?
        };
        Ok(res)
    }
}

#[async_trait]
impl<F> Middleware for F
where
    F: Send
        + Sync
        + 'static
        + for<'a> Fn(Request, Next<'a>) -> Pin<Box<dyn Future<Output = crate::Result> + 'a + Send>>,
{
    async fn handle(&self, req: Request, next: Next<'_>) -> crate::Result {
        (self)(req, next).await
    }
}
